<?php
namespace common\models\recharge;

use common\models\Common;
use common\models\Functions;
use common\models\Status;
use yii\db\Exception;
use Yii;

/**
 * Created by PhpStorm.
 * Time: 4:12 PM
 */
class RechaegeType extends Common
{
    public static function tableName()
    {
        return '{{%recharge_type}}';
    }

    /**
     * 更新库存
     * @param $num
     * @param $goodsId
     * @throws Exception
     */
    public static function editStock($num,$goodsId)
    {
        $res = static::updateAllCounters(['stock' => $num], ['id'=>$goodsId]);
        if($res === false){
            throw new Exception("商品库存更新失败");
        }
    }
    /**
     * 启用禁用 等切换装填
     * @param array $statusMap
     * @param string $filed
     * @return array
     */
    public function switchStatus($statusMap = [], $filed = 'status') {
        try {
            $post = Yii::$app->request->post();

            $id = (int) $post['id'];
            if (empty($id)) {
                throw new Exception('未知信息');
            }
            $statusMap = $statusMap ? $statusMap : Status::commonStatusMap();
            $filed = $filed ? $filed : 'status';

            $afterStatus = (int) $post['status'];
            $afterStatusName = $statusMap[$afterStatus];

            $data[$filed] = $afterStatus;
            $data['update_time'] = date("Y-m-d H:i:s");
            $res = static::updateData($data, ['id' => $id]);
            if ($res === false) {
                throw new Exception($afterStatusName.'失败，请联系开发小哥哥');
            }
            return Functions::formatRestAPI(0, $afterStatusName.'成功');
        } catch (\yii\base\Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }
}
